package com.example.ndktest;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import org.apache.http.conn.util.InetAddressUtils;

import android.support.v7.app.ActionBarActivity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {
	
	private static final int DEFAULT_COMPRESSION = 8;
	
	private String strIP;
	private String strPort;
	private EditText tvIP;
	private EditText tvPort;
	private ClientManager clientMgr = new ClientManager();
	private TextView tvPTT;
	private TextView tvMyIP;
	public static boolean app_running;
	private AudioPlayer audioPlayer;
	public final static int GUIUPDATEIDENTIFIER = 0;
	private static TextView tvLog;
	
	public static FileLoger fileLoger;
	public static Handler myHandler = new Handler() {  
	        public void handleMessage(Message msg) {   
	             switch (msg.what) {   
	                  case MainActivity.GUIUPDATEIDENTIFIER:   
	                       if(tvLog != null)
	                       {
	                    	   tvLog.setText(msg.getData().getString("Log"));
	                       }
	                       break;   
	             }   
	             super.handleMessage(msg);   
	        }   
	};
	
	public static void sendMsgToUI(String msg)
	{
		Message message = new Message();
		Bundle bundle = new Bundle();
		bundle.putString("Log", String.valueOf(msg));
		message.setData(bundle);
		message.what = MainActivity.GUIUPDATEIDENTIFIER;
		MainActivity.myHandler.sendMessage(message);
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initViews();
		initClientManager();
		initAudioPlayer();
		
		app_running = true;
	}
	
	public void initViews()
	{
		tvIP = (EditText)findViewById(R.id.input_ip);
		tvPort = (EditText)findViewById(R.id.input_port);
		tvPTT = (TextView)findViewById(R.id.txt_talk);
		tvMyIP = (TextView)findViewById(R.id.txt_my_ip);
		tvMyIP.setText("My IP: " + getIPadd());
		tvLog = (TextView)findViewById(R.id.txt_log);
	}
	
	public void initClientManager()
	{
		clientMgr.setMode(ClientManager.NETONLY);
		clientMgr.setRunning(true);
		Thread cmThread = new Thread(clientMgr);
		cmThread.start();
		
		fileLoger = new FileLoger();
		fileLoger.init();
		fileLoger.setRecording(true);
		Thread fileLogerThread = new Thread(fileLoger);
		fileLogerThread.start();
	}
	
	public void initAudioPlayer()
	{
		audioPlayer = new AudioPlayer();
		Thread audioPlayerThread = new Thread(audioPlayer);
		audioPlayerThread.start();
	}
	
	public String getIPadd(){
    	String IP_Address;
	    try {  
	         Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); 
	         while(en.hasMoreElements()) 
	           {  
	             NetworkInterface intf = en.nextElement();  
	             Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); 
	             while(enumIpAddr.hasMoreElements()) 
	             {  
	            	InetAddress inetAddress = enumIpAddr.nextElement();  
	                if (!inetAddress.isLoopbackAddress()&& InetAddressUtils.isIPv4Address(IP_Address=inetAddress.getHostAddress())) 
	                {  
	                    return IP_Address;  
	                }  
	            }  
	        }  
	    } catch (SocketException ex) { 
	    	
	  ;
	    }  
	    return "No connection to Network";
    }

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	private void startTalking()
	{
		String ipAddr = tvIP.getText().toString();
		String portNum = tvPort.getText().toString();
		if((ipAddr.length() == 0) || (portNum.length() == 0))
		{
			Toast.makeText(this, "IP or Port is empty", Toast.LENGTH_SHORT).show();
		}
		
		clientMgr.netClientInit(ipAddr, Integer.parseInt(portNum));
		clientMgr.setRecording(true);
		
		this.tvPTT.setText("Talking");
	}
	
	private void endTalking()
	{
		clientMgr.setRecording(false);
		this.tvPTT.setText("Push To Talk");
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
    	if (keyCode==KeyEvent.KEYCODE_VOLUME_DOWN) {
    		startTalking();
    		return true;
		}else if(keyCode==KeyEvent.KEYCODE_VOLUME_UP){
			startTalking();
			return true;
		}else if(keyCode==KeyEvent.KEYCODE_BACK){
			app_running = false;
			fileLoger.setRecording(false);
			this.finish();
		}
		return super.onKeyDown(keyCode, event);
	}
	
	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode==KeyEvent.KEYCODE_VOLUME_DOWN) {
			endTalking();
    		return true;
		}else if(keyCode==KeyEvent.KEYCODE_VOLUME_UP){
			endTalking();
			return true;
		}
		return super.onKeyUp(keyCode, event);
	}
}
